package com.zll.dms.aop;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zll.dms.pojo.ResultData;
import com.zll.dms.utils.CosrUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.session.UnknownSessionException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 统一异常处理
 */
@Slf4j
public class MyExceptionHandler implements HandlerExceptionResolver {
    @SneakyThrows
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        CosrUtils.handlerCosr(httpServletResponse,httpServletRequest);
        ResultData noLogin;
        //未登录
        if (e instanceof UnauthenticatedException || e instanceof AuthenticationException || e instanceof UnknownSessionException) {
            noLogin = ResultData.createNoLogin();
        }else if (e instanceof UnauthorizedException || e instanceof AuthorizationException) {
            //无权限
            noLogin = ResultData.createNoRight();
        }else {
            //其他异常
            log.error("异常",e);
            noLogin=ResultData.error("系统出错啦，请联系管理员");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(noLogin);
        PrintWriter writer = httpServletResponse.getWriter();
        writer.write(s);
        writer.flush();
        writer.close();
        return modelAndView;
    }
}
